package com.hxd.otc.module.wallet.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.dialog.MultipleBlocksDialog;
import com.hxd.otc.module.my.activity.SecurityCenterActivity;
import com.hxd.otc.module.wallet.bean.WalletCurrencyBean;
import com.hxd.otc.module.wallet.contract.WalletCoinWithdrawContract;
import com.hxd.otc.module.wallet.presenter.CoinWithdrawPresenter;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.utils.ConvertUtil;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.BlocksToast;
import com.hxd.otc.widget.LimitNumberTextWatcher;
import com.hxd.otc.widget.TitleBar;
import com.hxd.otc.widget.WalletDialogTipsUtil;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.List;

import butterknife.BindView;

/**
 * 描  述 :  提币
 */
public class CoinWithdrawActivity extends PermissionActivity<CoinWithdrawPresenter> implements WalletCoinWithdrawContract.View {
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.et_coin_withdraw_num)
    EditText etCoinWithdrawNum;
    @BindView(R.id.et_coin_withdraw_address)
    EditText etCoinWithdrawAddress;
    @BindView(R.id.iv_scan_qr_code)
    ImageView ivScanQrCode;
    @BindView(R.id.tv_withdraw_tips)
    TextView tvWithdrawTips;
    @BindView(R.id.tv_withdraw_address)
    TextView tvWithdrawAddress;
    @BindView(R.id.iv_wallet_contact)
    ImageView ivWalletContact;
    @BindView(R.id.tv_fee_rule)
    TextView mTvFeeRule;
    @BindView(R.id.et_google_code)
    EditText etGoogleCode;
    @BindView(R.id.tv_sure)
    TextView tvSure;


    private static String[] PERMISSION = {Manifest.permission.CAMERA};
    /**
     * 扫描跳转Activity RequestCode
     */
    public static final int REQUEST_CODE = 111;

    /**
     * 钱包地址
     */
    public static final int REQUEST_CODE_WALLET_ADDRESS = 1;

    private WalletCurrencyBean walletCurrencyBean;
    private MultipleBlocksDialog mDailog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_wallet_coin_withdraw;
    }

    @Override
    protected CoinWithdrawPresenter createPresenter() {
        return new CoinWithdrawPresenter(this);
    }

    @Override
    protected void initView() {
        walletCurrencyBean = (WalletCurrencyBean) getIntent().getExtras().getSerializable("walletCurrencyBean");
        etCoinWithdrawAddress.setHint(getString(R.string.enter_coin_address, walletCurrencyBean.getName()));
    }

    @Override
    protected void initData() {
        updateOverallUI();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initEvent() {

        etCoinWithdrawNum.addTextChangedListener(new LimitNumberTextWatcher(etCoinWithdrawNum, 9, 8) {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                updateOverallUI();
            }
        });

        ivWalletContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString(WalletContactActivity.EXTRA_FILTER_COIN_TYPE, walletCurrencyBean.getName());
                bundle.putString(WalletContactActivity.EXTRA_FILTER_COIN_ID, walletCurrencyBean.getId());
                bundle.putBoolean(WalletContactActivity.EXTRA_IS_SHOW_ADD, false);
                bundle.putInt(WalletContactActivity.EXTRA_OPEN_SOURCE, WalletContactActivity.EXTRA_OPEN_SOURCE_COIN_WITHDRAW);
                $startActivityForResult(WalletContactActivity.class, bundle, CoinWithdrawActivity.REQUEST_CODE_WALLET_ADDRESS);
            }
        });

        //扫描图片
        ivScanQrCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermission();
            }
        });

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkDataAndWithdraw();
            }
        });

        //没设置交易密码点击edittext弹出对话框
        etGoogleCode.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_UP:

                        if (!UserHelper.isSetGoogleAuth()) {
                            mDailog = new MultipleBlocksDialog(CoinWithdrawActivity.this);
                            mDailog.setContent(getString(R.string.without_google_verified));
                            mDailog.setTitle(getString(R.string.wallet_google_verified_title));
                            mDailog.setTvCancle(getString(R.string.cancel));
                            mDailog.setTvSure(getString(R.string.wallet_common_ok), new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mDailog.dismiss();
                                    Intent intent = new Intent(CoinWithdrawActivity.this, SecurityCenterActivity.class);
                                    startActivity(intent);
                                }
                            });
                            mDailog.show();
                        }
                        break;
                }
                return false;
            }
        });

    }

    String mVerifyCode;

    private void checkDataAndWithdraw() {
        String nums = etCoinWithdrawNum.getText().toString().trim();
        String address = etCoinWithdrawAddress.getText().toString().trim();
        mVerifyCode = etGoogleCode.getText().toString().trim();
        if (TextUtils.isEmpty(nums)) {
            BlocksToast.get().showToast(R.string.wallet_toast_withdraw_empty_nums);
            return;
        }
        if (TextUtils.isEmpty(address)) {
            BlocksToast.get().showToast(R.string.wallet_toast_withdraw_empty_address);
            return;
        }

        try {
            double withdraw_num = ConvertUtil.convertToDouble(nums);
            if (withdraw_num < walletCurrencyBean.withdrawMinVolume) {
                BlocksToast.get().showToast(R.string.wallet_toast_withdraw_min_not_enough_nums);
                return;
            }
            if (withdraw_num > walletCurrencyBean.withdrawMaxVolume) {
                BlocksToast.get().showToast(R.string.wallet_toast_withdraw_not_enough_nums);
                return;
            }
        } catch (Exception e) {
            BlocksToast.get().showToast(R.string.wallet_toast_withdraw_error_nums);
            return;
        }
        if (TextUtils.isEmpty(mVerifyCode)) {
            BlocksToast.get().showToast(R.string.code_not_null);
            return;
        }
        mPresenter.coinWithdraw(walletCurrencyBean.getId(), walletCurrencyBean.getName(),
                address, nums);
    }

    private void requestPermission() {
        super.requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                if (PERMISSION.length == allowPermissions.size()) {
                    $startActivityForResult(CommonCaptureActivity.class, REQUEST_CODE);
                }
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {
                WalletDialogTipsUtil.showCameraTipsDialog(CoinWithdrawActivity.this);
            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
                WalletDialogTipsUtil.showCameraTipsDialog(CoinWithdrawActivity.this);
            }

            @Override
            public void onLowVersion() {
                $startActivityForResult(CommonCaptureActivity.class, REQUEST_CODE);
            }
        }, PERMISSION);
    }


    @Override
    public void transferSuccess(String id) {
        if (TextUtils.isEmpty(id)) {
            showToast(getString(R.string.failed_to_withdraw_coins));
            return;
        }
        mPresenter.postGooleValidate(id, mVerifyCode);

    }

    //提币成功
    @Override
    public void Success() {
        etCoinWithdrawNum.setText("");
        BlocksToast.get().showToast(R.string.wallet_toast_withdraw_success);
        setResult(RESULT_OK);
        finish();
    }


    @Override
    public void setTransferEnable(boolean b) {
    }

    /**
     * 更新整体ui
     */
    private void updateOverallUI() {
        titleBar.getTitle().setText(getString(R.string.coin_withdraw_title, walletCurrencyBean.getName()));

        tvWithdrawAddress.setText(String.format(getString(R.string.wallet_withdraw_address_tips), walletCurrencyBean.getName()));

        etCoinWithdrawNum.setHint(String.format(getString(R.string.wallet_withdraw_nums_hint_tips), walletCurrencyBean.getName()) + ": " + StringUtil.format8Number(walletCurrencyBean.volume));

        StringBuilder sb = new StringBuilder();
//
        //修改文案提示
        updateTvWithdrawTip(walletCurrencyBean.getName(), sb);

        //当输入金额为空时不现实手续费提示
        String withdrawNumStr = etCoinWithdrawNum.getText().toString();
        if (TextUtils.isEmpty(withdrawNumStr)) {
            mTvFeeRule.setText(getString(R.string.handling_fee, "0", walletCurrencyBean.getName()));
        } else {
            if (walletCurrencyBean.withdrawFeeType == 1) {
                mTvFeeRule.setText(getString(R.string.handling_fee, walletCurrencyBean.withdrawFee + "", walletCurrencyBean.getName()));
            } else {
                mTvFeeRule.setText(getString(R.string.handling_fee,
                        walletCurrencyBean.withdrawFee * Double.valueOf(etCoinWithdrawNum.getText().toString()) + "",
                        walletCurrencyBean.getName()));
            }

        }

        return;
    }

    /**
     * 更新提示文案
     *
     * @param selectCoinType
     * @param sb
     */
    private void updateTvWithdrawTip(String selectCoinType, StringBuilder sb) {
        sb.append(getString(R.string.withdrawal_tip1))
                .append("<font color=\"#417FDB\">").append(StringUtil.handleZero(walletCurrencyBean.withdrawMinVolume + ""))
                .append("-").append(StringUtil.handleZero(walletCurrencyBean.withdrawMaxVolume + "")).append("</font>")
                .append(" ").append(selectCoinType).append("</font>")
                .append("<br/>").append("<br/>")
                .append(getString(R.string.withdrawal_tip2)).append("<font color=\"#417FDB\">").append(selectCoinType).append("</font>")
                .append(getString(R.string.withdrawal_tip3));
        tvWithdrawTips.setText(Html.fromHtml(sb.toString()));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    etCoinWithdrawAddress.setText(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    BlocksToast.get().showToast(R.string.wallet_toast_scan_code_re_fail);
                }
            }
        } else if (requestCode == REQUEST_CODE_WALLET_ADDRESS) {
            if (data == null) return;
            etCoinWithdrawAddress.setText(data.getStringExtra(WalletContactActivity.RESULT_EXTRA_ADDRESS));
        }
    }

    @Override
    public void onShowLoading() {
        showSpinnerDlg(null, false);
    }

    @Override
    public void onHideLoading() {
        dismissSpinnerDlg();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UIUtils.dismissDialog(mDailog);
    }
}
